package com.sctvcloud.qingchuan.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.mob.tools.utils.DeviceHelper;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by liuyu on 2017/8/14.
 */

public class DeviceIdUtil {
    public static String getDeviceId(Context context){
        return "sidalndoaenltn3433okelsj";
    }

    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }
    public static String getId(Context ctx){
        if(!TextUtils.isEmpty(DeviceHelper.getInstance(ctx).getDeviceId())){
            return  DeviceHelper.getInstance(ctx).getDeviceId();
        }else if(!TextUtils.isEmpty(DeviceHelper.getInstance(ctx).getIMEI())){
            return  DeviceHelper.getInstance(ctx).getIMEI();
        }else if(!TextUtils.isEmpty(DeviceHelper.getInstance(ctx).getIMSI())){
            return  DeviceHelper.getInstance(ctx).getIMSI();
        }else if(!TextUtils.isEmpty(DeviceHelper.getInstance(ctx).getAndroidID())){
            return  DeviceHelper.getInstance(ctx).getAndroidID();
        }else{
            return DeviceHelper.getInstance(ctx).getLine1Number();
        }

    }
    /**
     * 获取app当前的渠道号或application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String channelNumber = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelNumber = applicationInfo.metaData.getString(key);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelNumber;
    }

}
